/**
 * 
 */
package com.nari.basic.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.nari.basic.model.IUser;
import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.platform.security.MD5Encoder;

/**
 * 
 * @author Xiaopeng
 * @date 2013-7-18
 */
public class UserDaoImpl extends GenericDaoImpl<IUser, String> implements IUserDao {
	private String sysDefaultPwd;

	/**
	 * 用户登录
	 * @param userID
	 * @param password
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-22
	 */
	public IUser queryLoginUser(String userID, String password) throws Exception {
		if (userID != null && !"".equals(userID)) {
			String loginHql = "from IUser u where u.userID='" + userID + "' "
					+ "and u.password='" + password + "'";
			List<IUser> userList = this.runQueryHSql(loginHql);
			if (userList != null && userList.size() > 0) {
				return userList.get(0);
			}
		}
		return null;
	}

	/**
	 * 根据分页等信息查询用户列表
	 * @param userID 用户登录姓名（可选）
	 * @param pid 用户身份证号（可选）
	 * @param pageCond 分页信息
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-24
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IUser> queryUserWithResultPage(String userID,
			String pid, PageCond pageCond) throws Exception {
		// 用户列表查询
		Criteria listCriteria = this.getCurrentSession().createCriteria(IUser.class);
		// 结果集个数查询
		Criteria countCriteria = this.getCurrentSession().createCriteria(IUser.class);
		// 条件查询（可选）
		if (userID != null && !"".equals(userID.trim())) {
			listCriteria.add(Restrictions.ilike("userID", userID.trim(), MatchMode.ANYWHERE));
			countCriteria.add(Restrictions.ilike("userID", userID.trim(), MatchMode.ANYWHERE));
		}
		if (pid != null && !"".equals(pid.trim())) {
			listCriteria.add(Restrictions.ilike("pid", pid.trim(), MatchMode.START));
			countCriteria.add(Restrictions.ilike("pid", pid.trim(), MatchMode.START));
		}
		// 结果集排序
		listCriteria.addOrder(Order.asc("userID"));
		// 分页查询
		listCriteria.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		// 统计结果集个数
		int total = ((Long)countCriteria.setProjection(Projections.rowCount()).list().get(0)).intValue();
		pageCond.setTotal(total);
		// 构造返回类型
		ResultWithPageCond<IUser> userPage = new ResultWithPageCond<IUser>();
		userPage.setList(listCriteria.list());
		userPage.setPageCond(pageCond);
		return userPage;
	}

	/**
	 * 通过角色唯一标识查询用户列表
	 * @param roleUID 角色唯一标识，若为指定角色唯一标识，则返回空
	 * @param userID 用户名（可选）
	 * @param pid 身份证号（可选）
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-26
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IUser> queryUserByRoleUID(String roleUID,
			String userID, String pid, PageCond pageCond) throws Exception {
		// 构造返回类型
		ResultWithPageCond<IUser> userPage = new ResultWithPageCond<IUser>();
		if (roleUID == null || "".equals(roleUID.trim())) {
			userPage.setList(null);
			userPage.setPageCond(pageCond);
			return userPage;
		}
		StringBuffer roleUserQuery = new StringBuffer("from IUser u ");
		roleUserQuery.append("where u.id in");
		roleUserQuery.append("(select ur.userUuid ");
		roleUserQuery.append("from IUserRole ur ");
		roleUserQuery.append("where ur.roleUuid='");
		roleUserQuery.append(roleUID);
		roleUserQuery.append("') ");
		if (userID != null && !"".equals(userID.trim())) {
			roleUserQuery.append("and lower(u.userID) like '%");
			roleUserQuery.append(userID.toLowerCase());
			roleUserQuery.append("%' ");
		}
		if (pid != null && !"".equals(pid.trim())) {
			roleUserQuery.append("and lower(u.pid) like '");
			roleUserQuery.append(pid.toLowerCase());
			roleUserQuery.append("%' ");
		}
		roleUserQuery.append("order by u.userID");
		// 查询结果集个数
		String resultNumQuery = "select count(*) " + roleUserQuery.toString();
		int total = ((Long) this.getCurrentSession().createQuery(resultNumQuery).uniqueResult()).intValue();
		pageCond.setTotal(total);
		// 分页查询
		Query pageQuery = this.getCurrentSession().createQuery(roleUserQuery.toString());
		pageQuery.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		// 构造返回类型
		userPage.setList(pageQuery.list());
		userPage.setPageCond(pageCond);
		return userPage;
	}

	/**
	 * 查询没有授权指定权限的带分页的用户列表
	 * @param roleUID 角色唯一标识，若为指定角色唯一标识，则返回空
	 * @param userID 用户名（可选）
	 * @param pid 身份证号（可选）
	 * @param pageCond 分页信息
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-29
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IUser> queryUserPageWithoutRole(String roleUID,
			String userID, String pid, PageCond pageCond) throws Exception {
		// 构造返回类型
		ResultWithPageCond<IUser> userPage = new ResultWithPageCond<IUser>();
		if (roleUID == null || "".equals(roleUID.trim())) {
			userPage.setList(null);
			userPage.setPageCond(pageCond);
			return userPage;
		}
		StringBuffer roleUserQuery = new StringBuffer("from IUser u ");
		roleUserQuery.append("where u.id not in");
		roleUserQuery.append("(select ur.userUuid ");
		roleUserQuery.append("from IUserRole ur ");
		roleUserQuery.append("where ur.roleUuid='");
		roleUserQuery.append(roleUID);
		roleUserQuery.append("') ");
		if (userID != null && !"".equals(userID.trim())) {
			roleUserQuery.append("and lower(u.userID) like '%");
			roleUserQuery.append(userID.toLowerCase());
			roleUserQuery.append("%' ");
		}
		if (pid != null && !"".equals(pid.trim())) {
			roleUserQuery.append("and lower(u.pid) like '");
			roleUserQuery.append(pid.toLowerCase());
			roleUserQuery.append("%' ");
		}
		roleUserQuery.append("order by u.userID");
		// 查询结果集个数
		String resultNumQuery = "select count(*) " + roleUserQuery.toString();
		int total = ((Long) this.getCurrentSession().createQuery(resultNumQuery).uniqueResult()).intValue();
		pageCond.setTotal(total);
		// 分页查询
		Query pageQuery = this.getCurrentSession().createQuery(roleUserQuery.toString());
		pageQuery.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		// 构造返回类型
		userPage.setList(pageQuery.list());
		userPage.setPageCond(pageCond);
		return userPage;
	}
	
	/**
	 * 通过用户登录名查询用户信息
	 * @param userID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-12
	 */
	public IUser queryUserInfoByUserID(String userID) throws Exception {
		String hsql = "from IUser u " +
				"where u.userID='"+userID+"'";
		List<IUser> userList = this.runQueryHSql(hsql);
		//用户信息
		IUser user = null;
		if(userList!=null && userList.size()>0) {
			user = userList.get(0);
		}
		return user;
	}
	
	/**
	 * 通过角色编号查询对应的用户列表
	 * @param roleID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-23
	 */
	public List<IUser> queryUserListByRoleID(String roleID) throws Exception {
		String hsql = "from IUser u " +
				"where u.id in(select ur.userUuid " +
							"from IUserRole ur " +
							"where ur.roleUuid=(select r.id " +
											"from IRole r " +
											"where r.roleID='"+roleID+"'))";
		return this.runQueryHSql(hsql);
	}

	/**
	 * 新增或修改系统用户信息
	 * @param userID
	 * @return 返回更新的用户信息
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-23
	 */
	public IUser saveOrUpdateUser(String userID) throws Exception {
		IUser user = this.queryUserInfoByUserID(userID);
		if(user == null) {
			user = new IUser();
			//默认初始密码
			String password = MD5Encoder.getMD5String(this.sysDefaultPwd);
			user.setPassword(password);
		}
		//设置用户登录名
		user.setUserID(userID);
		//用户姓名
		user.setUserName(userID);
		//状态：有效
		user.setStatus("1");
		this.saveOrUpdateEntity(user);
		return user;
	}
	
	/**
	 * 统计相同用户名的用户个数(排除指定的用户)
	 * @param userID 用户名
	 * @param userUuid 指定用户的唯一标识
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-7-18
	 */
	public int countUsersByUserID(String userID, String userUuid) throws Exception {
		String hsql = "select count(*) from IUser u " +
				"where u.userID='"+userID+"'";
		if(userUuid!=null && !"".equals(userUuid)) {
			hsql += " and u.id<>'"+userUuid+"'";
		}
		return ((Long)this.getCurrentSession().createQuery(hsql).uniqueResult()).intValue();
	}

	/**
	 * @return the sysDefaultPwd
	 */
	public String getSysDefaultPwd() {
		return sysDefaultPwd;
	}

	/**
	 * @param sysDefaultPwd the sysDefaultPwd to set
	 */
	public void setSysDefaultPwd(String sysDefaultPwd) {
		this.sysDefaultPwd = sysDefaultPwd;
	}
	
}
